#include "ElementSwitch.h"

ElementSwitch::ElementSwitch(vector3<int> pos)
{
    type=SWITCH;
    geometry = AABB(vector3<float>(0,0,0),vector3<float>(1,1,1));
    translate(pos.cast<float>());

    activated=false;
    isCollidable=false;
    aniObj.stop();
}

void ElementSwitch::invokeCollisionEvent(Character*){

}

void ElementSwitch::invokeUpdateEvent(Character *c){

}

void ElementSwitch::invokeActivateEvent(){
    if(!activated)activate();
    else deactivate();
}

void ElementSwitch::activate(){
    if(activated)return;

    activated=true;
    for(int i=0;i<targets.size();i++)
        targets[i]->activate();

    aniObj.playForward();
    aniObj.reset();
    aniObj.setOn(true);
}

void ElementSwitch::deactivate(){
    if(!activated)return;

    activated=false;
    for(int i=0;i<targets.size();i++)
        targets[i]->deactivate();

    aniObj.playReverse();
    aniObj.reset();
    aniObj.setOn(false);
}

void ElementSwitch::render(){
    glPushMatrix();
    glTranslatef(s.position.x,s.position.y,s.position.z);
    aniObj.render();
    glPopMatrix();
}

void ElementSwitch::editorModeRender(){
    render();

    glPushMatrix();
    glColor3f(0,1,0);
    glLineWidth(3);
    glDisable(GL_LIGHTING);
    glBegin(GL_LINES);
    for(int i=0;i<targets.size();i++)
    {
        glVertex3f(geometry.center.x,geometry.center.y,geometry.center.z);
        glVertex3f(targets[i]->geometry.center.x,targets[i]->geometry.center.y,targets[i]->geometry.center.z);
    }
    glEnd();
    glEnable(GL_LIGHTING);
    glPopMatrix();
}

void ElementSwitch::addTarget(GameElement * ge){
    if(targets.size()<MAX_TARGETS)
        targets.push(ge);
}

void ElementSwitch::removeTarget(GameElement *ge){
    GameElement* temp;

    if(!targets.empty())
    {
        temp=targets.pop();
        if(temp==ge)return;
    }
    if(targets.empty())return;

    for(int i=0;i<targets.size();i++)
    {
        if(targets[i]==ge)
        {
        targets[i]=temp;
        return;
        }
    }
    targets.push(temp);
}

void ElementSwitch::removeTarget(int index){
    if(index<targets.size())
    {
        if(index==targets.size()-1)targets.pop();
        else targets[index]=targets.pop();
    }
}

ElementSwitch::~ElementSwitch()
{
    for(int i=0;i<targets.size();i++)
        targets[i]=0;
}
